﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Workflow;
using Microsoft.Crm.Sdk;
using System.Net.NetworkInformation;
using System.Net;
using System.Workflow.ComponentModel.Compiler;

namespace CrmContrib.Workflow.Activities.Networking
{
    [CrmWorkflowActivity("Ping", "CrmContrib \\ Networking")]
    public class PingActivity : Activity
    {
        [CrmInput("Address")]
        [ValidationOption(ValidationOption.Required)]
        public string Address
        {
            get { return (string)base.GetValue(PingActivity.AddressProperty); }
            set { base.SetValue(PingActivity.AddressProperty, value); }
        }

        public static readonly DependencyProperty AddressProperty = DependencyProperty.Register("Address", typeof(string), typeof(PingActivity));

        [CrmInput("Timeout")]
        [ValidationOption(ValidationOption.Optional)]
        public CrmNumber Timeout
        {
            get { return (CrmNumber)base.GetValue(PingActivity.TimeoutProperty); }
            set { base.SetValue(PingActivity.TimeoutProperty, value); }
        }

        public static readonly DependencyProperty TimeoutProperty = DependencyProperty.Register("Timeout", typeof(CrmNumber), typeof(PingActivity));

        [CrmOutput("Status")]
        public string Status
        {
            get { return (string)base.GetValue(PingActivity.StatusProperty); }
            set { base.SetValue(PingActivity.StatusProperty, value); }
        }

        public static readonly DependencyProperty StatusProperty = DependencyProperty.Register("Status", typeof(string), typeof(PingActivity));

        [CrmOutput("Roundtrip Time")]
        public CrmNumber RoundtripTime
        {
            get { return (CrmNumber)GetValue(PingActivity.RoundtripTimeProperty); }
            set { SetValue(PingActivity.RoundtripTimeProperty, value); }
        }
        
        public static readonly DependencyProperty RoundtripTimeProperty = DependencyProperty.Register("RoundtripTime", typeof(CrmNumber), typeof(PingActivity));

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            using (var ping = new Ping())
            {
                var reply = this.Timeout.IsNull ? ping.Send(this.Address, this.Timeout.Value) : ping.Send(this.Address);
                this.Status = reply.Status.ToString();
                this.RoundtripTime = new CrmNumber((int)reply.RoundtripTime);
            }

            return base.Execute(executionContext);
        }
    }
}
